<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/17
 * Time: 11:34
 */

namespace app\admin\controller;

use think\Db;
use think\Validate;

/*
 * 广告联系
 * */

class ads extends Base
{

    public function index()
    {
        $num = Db::name('ads')
            ->count();
        $pageObject = new \Page($num);

        $list = Db::name('ads')
            ->select();

        $group_list = Db::name('ad_position')
            ->select();
        $map = array(
            'num' => $num,
            'list' => $list,
            'page' => $pageObject->showPages(),
            'group_list' => $group_list
        );
        return view('index', $map);
    }

    public function add()
    {
        $validate = new Validate([
            ['name', 'require|unique:ads', '广告名称必填|广告名称不能重复！'],
            ['start_time', 'require', '开始时间必填'],
            ['end_time', 'require', '结束时间必填'],
            ['end_time', 'before:input("start_time")', '结束时间必须大于开始时间'],
            ['link', 'require', '广告图片必必须上传'],
        ]);

        if (!$validate->check($_POST)) {
            $this->error($validate->getError());
        }
        $data = $_POST;
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);
        $data['create_time'] = time();
        if ($id = Db::name('ads')->insertGetId($data)) {
            $this->success('添加广告成功！');
        } else {
            $this->error('添加广告失败！');
        }
    }

    public function del()
    {
        if (Db::name('ads')->delete(input('id'))) {
            $this->success('当前分类删除成功', url('admin/ads/index'));
        } else {
            $this->error('当前分类删除失败');
        }

    }

    public function edit()
    {
        if (!$_POST) {
            $id = input('id');
            $list = Db::name('ads')
                ->where(array('id' => $id))
                ->find();

            $group = Db::name('ad_position')
                ->select();
            $map = array(
                'list' => $list,
                'group_list' => $group
            );
            return view('edit', $map);
        } else {
            $validate = new Validate([
                ['name', 'require|unique:menu', '分类名称必填|菜单名称重复'],
            ]);
            if (!$validate->check($_POST)) {
                $this->error($validate->getError());
            }
            $add_data = $_POST;
            $add_data['update_time'] = time();
            $add_data['start_time'] = strtotime($add_data['start_time']);
            $add_data['end_time'] = strtotime($add_data['end_time']);
            if ($id = Db::name('ads')->update($add_data)) {
                /* rm_cache_menu();*/
                $this->success('分类修改成功');
            } else {
                $this->success('分类修改失败');
            }
        }
    }

}